<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>76-网络请求常用对象 | 小黑博客</title><meta name="keywords" content="JavaScript,JavaScript高级程序设计第四版"><meta name="author" content="BluesYoung-web"><meta name="copyright" content="BluesYoung-web"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="常用对象 Headers Request Response  Headers 对象 所有外发请求和入站响应头部的容器 每个外发的 Request 实例都包含一个空的 Headers 实例，可以通过 Request.prototype.headers 访问 每个入站的 Response 实例也可以通过 Response.prototype.headers  12345678910111213&#x2F;&#x2F; 类">
<meta property="og:type" content="article">
<meta property="og:title" content="76-网络请求常用对象">
<meta property="og:url" content="https://bluesyoung-web.gitee.io/blog/2021-02-05-76-%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E5%B8%B8%E7%94%A8%E5%AF%B9%E8%B1%A1.html">
<meta property="og:site_name" content="小黑博客">
<meta property="og:description" content="常用对象 Headers Request Response  Headers 对象 所有外发请求和入站响应头部的容器 每个外发的 Request 实例都包含一个空的 Headers 实例，可以通过 Request.prototype.headers 访问 每个入站的 Response 实例也可以通过 Response.prototype.headers  12345678910111213&#x2F;&#x2F; 类">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png">
<meta property="article:published_time" content="2021-02-05T01:31:18.000Z">
<meta property="article:modified_time" content="2021-08-29T11:36:10.269Z">
<meta property="article:author" content="BluesYoung-web">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="JavaScript高级程序设计第四版">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://bluesyoung-web.gitee.io/blog/2021-02-05-76-%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E5%B8%B8%E7%94%A8%E5%AF%B9%E8%B1%A1"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: BluesYoung-web","link":"链接: ","source":"来源: 小黑博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '76-网络请求常用对象',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-08-29 19:36:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/background.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/css/custom.min.css"></link><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/hbs.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">小黑博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">76-网络请求常用对象</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-05T01:31:18.000Z" title="发表于 2021-02-05 09:31:18">2021-02-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T11:36:10.269Z" title="更新于 2021-08-29 19:36:10">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">JavaScript高级程序设计</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/%E7%AC%AC24%E7%AB%A0%E2%80%94%E2%80%94%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E4%B8%8E%E8%BF%9C%E7%A8%8B%E8%B5%84%E6%BA%90/">第24章——网络请求与远程资源</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>12分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="常用对象"><a href="#常用对象" class="headerlink" title="常用对象"></a>常用对象</h2><ul>
<li><code>Headers</code></li>
<li><code>Request</code></li>
<li><code>Response</code></li>
</ul>
<h2 id="Headers-对象"><a href="#Headers-对象" class="headerlink" title="Headers 对象"></a><code>Headers</code> 对象</h2><ul>
<li>所有外发请求和入站响应头部的容器</li>
<li>每个外发的 <code>Request</code> 实例都包含一个空的 <code>Headers</code> 实例，可以通过 <code>Request.prototype.headers</code> 访问</li>
<li>每个入站的 <code>Response</code> 实例也可以通过 <code>Response.prototype.headers</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 类似于 Map 对象</span></span><br><span class="line"><span class="keyword">const</span> h = <span class="keyword">new</span> Headers();</span><br><span class="line"><span class="comment">// 设置/更新键</span></span><br><span class="line">h.set(<span class="string">&#x27;foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>);</span><br><span class="line"><span class="comment">// 检查键</span></span><br><span class="line">h.has(<span class="string">&#x27;foo&#x27;</span>);</span><br><span class="line"><span class="comment">// 获取值</span></span><br><span class="line">h.get(<span class="string">&#x27;foo&#x27;</span>); <span class="comment">// bar</span></span><br><span class="line"><span class="comment">// 删除值</span></span><br><span class="line">h.delete(<span class="string">&#x27;foo&#x27;</span>);</span><br><span class="line"><span class="comment">// ------独有特性------</span></span><br><span class="line"><span class="comment">// 可以使用对象初始化</span></span><br><span class="line"><span class="comment">// 可以使用 append 方法添加多个值</span></span><br></pre></td></tr></table></figure>

<h3 id="头部护卫"><a href="#头部护卫" class="headerlink" title="头部护卫"></a>头部护卫</h3><ul>
<li>并非所有的 <code>HTTP</code> 头部都可以被客户端修改</li>
<li>不同的护卫设置会改变 <code>set/append/delete</code> 方法的默认行为</li>
<li>违反护卫限制会抛出 <code>TypeError</code></li>
</ul>
<table>
<thead>
<tr>
<th>护卫</th>
<th>使用情形</th>
<th>限制</th>
</tr>
</thead>
<tbody><tr>
<td><code>none</code></td>
<td>在通过构造函数创建 <code>Headers</code> 实例时激活</td>
<td>无</td>
</tr>
<tr>
<td><code>request</code></td>
<td>在通过构造函数初始化 <code>Request</code> 对象，且 <code>mode</code> 值为非 <code>no-cors</code> 时激活</td>
<td>不允许修改禁止修改的头部</td>
</tr>
<tr>
<td><code>request-no-cors</code></td>
<td>在通过构造函数初始化 <code>Request</code> 对象，且 <code>mode</code> 值为 <code>no-cors</code> 时激活</td>
<td>不允许修改非简单头部</td>
</tr>
<tr>
<td><code>response</code></td>
<td>在通过构造函数初始化 <code>Response</code> 对象时激活</td>
<td>不允许修改禁止修改的响应头</td>
</tr>
<tr>
<td><code>immutable</code></td>
<td>在通过 <code>error()</code> 或 <code>redirect()</code> 静态方法初始化 <code>Response</code> 对象时激活</td>
<td>不允许修改任何头部</td>
</tr>
</tbody></table>
<h2 id="Request-对象"><a href="#Request-对象" class="headerlink" title="Request 对象"></a><code>Request</code> 对象</h2><ul>
<li><code>new Request(url, configObj)</code></li>
</ul>
<h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 用指定的初始值创建 Request 对象</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span> &#125;));</span><br><span class="line"><span class="comment">// Request &#123;</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// cache: &quot;default&quot;</span></span><br><span class="line"><span class="comment">// credentials: &quot;same-origin&quot;</span></span><br><span class="line"><span class="comment">// destination: &quot;&quot;</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// integrity: &quot;&quot;</span></span><br><span class="line"><span class="comment">// keepalive: false</span></span><br><span class="line"><span class="comment">// method: &quot;POST&quot;</span></span><br><span class="line"><span class="comment">// mode: &quot;cors&quot;</span></span><br><span class="line"><span class="comment">// redirect: &quot;follow&quot;</span></span><br><span class="line"><span class="comment">// referrer: &quot;about:client&quot;</span></span><br><span class="line"><span class="comment">// referrerPolicy: &quot;&quot;</span></span><br><span class="line"><span class="comment">// signal: AbortSignal &#123;aborted: false, onabort: null&#125;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/&quot;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="克隆"><a href="#克隆" class="headerlink" title="克隆"></a>克隆</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> r1 = <span class="keyword">new</span> Request(<span class="string">&#x27;http://foo.com&#x27;</span>);</span><br><span class="line"><span class="comment">// 将实例作为参数直接传人，可得到副本(不保证完全一样)</span></span><br><span class="line"><span class="keyword">const</span> r2 = <span class="keyword">new</span> Request(r1); <span class="comment">// r2.url = http://foo.com</span></span><br><span class="line"><span class="comment">// 如果同时传入配置对象，则会覆盖源对象中同名的值</span></span><br><span class="line"><span class="keyword">const</span> r2 = <span class="keyword">new</span> Request(r1, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span> &#125;);</span><br><span class="line"><span class="comment">// r1.method = &#x27;GET&#x27;, r2.method = &#x27;POST&#x27;</span></span><br><span class="line"><span class="comment">// ----------------------------------------</span></span><br><span class="line"><span class="keyword">let</span> r1 = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line"><span class="keyword">let</span> r2 = r1.clone();</span><br><span class="line"><span class="built_in">console</span>.log(r1.url); <span class="comment">// https://foo.com/</span></span><br><span class="line"><span class="built_in">console</span>.log(r2.url); <span class="comment">// https://foo.com/</span></span><br><span class="line"><span class="built_in">console</span>.log(r1.bodyUsed); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(r2.bodyUsed); <span class="comment">// false </span></span><br></pre></td></tr></table></figure>

<h3 id="fetch-中使用"><a href="#fetch-中使用" class="headerlink" title="fetch 中使用"></a><code>fetch</code> 中使用</h3><ul>
<li>可以传入已经创建好的 <code>Request</code> 实例来代替 <code>URL</code></li>
<li>传入的配置对象可以覆盖请求对象的值</li>
<li><strong>请求体已经使用过</strong>的 <code>Request</code> 对象不能用来发送请求，不包含请求体的不受限制</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>);</span><br><span class="line"><span class="comment">// 向 foo.com 发送 GET 请求</span></span><br><span class="line">fetch(r);</span><br><span class="line"><span class="comment">// 向 foo.com 发送 POST 请求</span></span><br><span class="line">fetch(r, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span> &#125;);</span><br><span class="line"><span class="comment">// --------------------------</span></span><br><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line">r.text();</span><br><span class="line">fetch(r);</span><br><span class="line"><span class="comment">// TypeError: Cannot construct a Request with a Request object that has already been used</span></span><br><span class="line"><span class="comment">// ---------------------------</span></span><br><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line">fetch(r); <span class="comment">// 使用之后会将请求体标记为已使用</span></span><br><span class="line">fetch(r);</span><br><span class="line"><span class="comment">// TypeError: Cannot construct a Request with a Request object that has already been used</span></span><br><span class="line"><span class="comment">// ---------------------------</span></span><br><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line"><span class="comment">// 3 个都会成功</span></span><br><span class="line">fetch(r.clone());</span><br><span class="line">fetch(r.clone());</span><br><span class="line">fetch(r);</span><br></pre></td></tr></table></figure>

<h2 id="Response-对象"><a href="#Response-对象" class="headerlink" title="Response 对象"></a><code>Response</code> 对象</h2><h3 id="创建-1"><a href="#创建-1" class="headerlink" title="创建"></a>创建</h3><ul>
<li>可以通过构造函数初始化 <code>Response</code> 对象且不需要参数</li>
<li>此时响应实例的属性均为默认值，因为它并不代表实际的 <code>HTTP</code> 响应</li>
<li>大多数情况下，产生 <code>Response</code> 对象的主要方式是调用 <code>fetch</code>，它返回一个最后会解决为 <code>Response</code> 对象的期约</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Response();</span><br><span class="line"><span class="built_in">console</span>.log(r);</span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: true</span></span><br><span class="line"><span class="comment">// redirected: false</span></span><br><span class="line"><span class="comment">// status: 200</span></span><br><span class="line"><span class="comment">// statusText: &quot;OK&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;default&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;&quot;</span></span><br><span class="line"><span class="comment">// &#125; </span></span><br><span class="line"><span class="comment">// ------------------------------</span></span><br><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>).then(<span class="function">(<span class="params">response</span>) =&gt;</span> <span class="built_in">console</span>.log(response));</span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: true</span></span><br><span class="line"><span class="comment">// redirected: false</span></span><br><span class="line"><span class="comment">// status: 200</span></span><br><span class="line"><span class="comment">// statusText: &quot;OK&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;basic&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/&quot;</span></span><br><span class="line"><span class="comment">// &#125; </span></span><br></pre></td></tr></table></figure>

<h4 id="Response-redirect"><a href="#Response-redirect" class="headerlink" title="Response.redirect()"></a><code>Response.redirect()</code></h4><ul>
<li>接收一个 <code>URL</code> 和一个重定向状态码(301,302,303,307,308)</li>
<li>返回重定向对象</li>
</ul>
<h4 id="Response-error"><a href="#Response-error" class="headerlink" title="Response.error()"></a><code>Response.error()</code></h4><ul>
<li>用于产生表示网络错误的 <code>Response</code> 对象</li>
</ul>
<h3 id="读取响应状态信息"><a href="#读取响应状态信息" class="headerlink" title="读取响应状态信息"></a>读取响应状态信息</h3><ul>
<li><code>Response</code> 对象包含一组只读属性：<ul>
<li><code>headers</code> 响应包含的 <code>Headers</code> 对象</li>
<li><code>ok</code> 布尔值，表示 <code>HTTP</code> 状态码的含义，200~299 为 <code>true</code>，其他为 <code>false</code></li>
<li><code>redirected</code> 布尔值，表示响应是否至少经过一次重定向</li>
<li><code>status</code> 整数，表示响应的 <code>HTTP</code> 状态码</li>
<li><code>statusText</code> 字符串，包含对 <code>HTTP</code> 状态码的正式描述</li>
<li><code>type</code>：<ul>
<li><code>basic</code> 表示标准的同源响应</li>
<li><code>cors</code> 表示标准的跨域响应</li>
<li><code>error</code> 表示响应对象是通过 <code>Response.error()</code> 创建的</li>
<li><code>opaque</code> 表示 <code>no-cors</code> 的 <code>fetch</code> 返回的跨域响应</li>
<li><code>opaqueredirect</code> 表示对 <code>redirect</code> 设置为 <code>manual</code> 的请求的响应</li>
</ul>
</li>
<li><code>url</code> 包含响应 <code>URL</code> 的字符串，对于重定向响应，这是最终的 <code>URL</code></li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;//foo.com&#x27;</span>).then(<span class="built_in">console</span>.log); <span class="comment">// 200</span></span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: true</span></span><br><span class="line"><span class="comment">// redirected: false</span></span><br><span class="line"><span class="comment">// status: 200</span></span><br><span class="line"><span class="comment">// statusText: &quot;OK&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;basic&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/&quot;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line">fetch(<span class="string">&#x27;//foo.com/redirect-me&#x27;</span>).then(<span class="built_in">console</span>.log); <span class="comment">// 302</span></span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: true</span></span><br><span class="line"><span class="comment">// redirected: true</span></span><br><span class="line"><span class="comment">// status: 200</span></span><br><span class="line"><span class="comment">// statusText: &quot;OK&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;basic&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/redirected-url/&quot;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line">fetch(<span class="string">&#x27;//foo.com/does-not-exist&#x27;</span>).then(<span class="built_in">console</span>.log); <span class="comment">// 404</span></span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: false</span></span><br><span class="line"><span class="comment">// redirected: true</span></span><br><span class="line"><span class="comment">// status: 404</span></span><br><span class="line"><span class="comment">// statusText: &quot;Not Found&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;basic&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/does-not-exist/&quot;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line">fetch(<span class="string">&#x27;//foo.com/throws-error&#x27;</span>).then(<span class="built_in">console</span>.log); <span class="comment">// 500</span></span><br><span class="line"><span class="comment">// Response &#123;</span></span><br><span class="line"><span class="comment">// body: (...)</span></span><br><span class="line"><span class="comment">// bodyUsed: false</span></span><br><span class="line"><span class="comment">// headers: Headers &#123;&#125;</span></span><br><span class="line"><span class="comment">// ok: false</span></span><br><span class="line"><span class="comment">// redirected: true</span></span><br><span class="line"><span class="comment">// status: 500</span></span><br><span class="line"><span class="comment">// statusText: &quot;Internal Server Error&quot;</span></span><br><span class="line"><span class="comment">// type: &quot;basic&quot;</span></span><br><span class="line"><span class="comment">// url: &quot;https://foo.com/throws-error/&quot;</span></span><br><span class="line"><span class="comment">// &#125; </span></span><br></pre></td></tr></table></figure>

<h3 id="克隆-1"><a href="#克隆-1" class="headerlink" title="克隆"></a>克隆</h3><ul>
<li>克隆 <code>Response</code> 对象的主要方式是使用 <code>clone()</code> 方法</li>
<li>这个方法会创建一个一模一样的副本，不会覆盖任何值，不会将任何请求的请求体标记为已使用</li>
<li>有响应体的 <code>Response</code> 对象<strong>只能读取一次</strong>，不包含响应体的 <code>Response</code> 对象不受此限制</li>
<li>要多次读取包含响应体的同一个 <code>Response</code> 对象，必须在<strong>第一次读取前</strong>调用 <code>clone()</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> r1 = <span class="keyword">new</span> Response(<span class="string">&#x27;foobar&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> r2 = r1.clone();</span><br><span class="line"><span class="built_in">console</span>.log(r1.bodyUsed); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(r2.bodyUsed); <span class="comment">// false</span></span><br><span class="line"><span class="comment">// ---------------------------</span></span><br><span class="line"><span class="keyword">let</span> r = <span class="keyword">new</span> Response(<span class="string">&#x27;foobar&#x27;</span>);</span><br><span class="line">r.clone(); <span class="comment">// 没有错误</span></span><br><span class="line">r.text(); <span class="comment">// 设置 bodyUsed 为 true</span></span><br><span class="line">r.clone(); <span class="comment">// TypeError:Failed to execute &#x27;clone&#x27; on &#x27;Response&#x27;: Response body is already used</span></span><br><span class="line"><span class="comment">// 伪克隆</span></span><br><span class="line"><span class="keyword">let</span> r1 = <span class="keyword">new</span> Response(<span class="string">&#x27;foobar&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> r2 = <span class="keyword">new</span> Response(r1.body);</span><br><span class="line"><span class="built_in">console</span>.log(r1.bodyUsed); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(r2.bodyUsed); <span class="comment">// false</span></span><br><span class="line">r2.text().then(<span class="built_in">console</span>.log); <span class="comment">// foobar</span></span><br><span class="line">r1.text().then(<span class="built_in">console</span>.log); <span class="comment">// TypeError: Failed to execute &#x27;text&#x27; on &#x27;Response&#x27;: body stream is locked</span></span><br></pre></td></tr></table></figure>

<h2 id="Body-混入"><a href="#Body-混入" class="headerlink" title="Body 混入"></a><code>Body</code> 混入</h2><ul>
<li><code>Request</code> 和 <code>Response</code> 都使用了 <code>Fetch API</code> 的 <code>Body</code> 混入，以实现两者承担有效载荷的能力</li>
<li>这个混入两个类型提供了：<ul>
<li><strong>只读</strong>的 <code>body</code> 属性，实现为可读流</li>
<li><strong>只读</strong>的 <code>bodyUsed</code> 布尔值，表示 <code>body</code> 流是否已读</li>
<li><code>.text()</code></li>
<li><code>.json()</code></li>
<li><code>.formData()</code></li>
<li><code>.arrayBuffer()</code></li>
<li><code>.blob()</code></li>
</ul>
</li>
</ul>
<h3 id="text"><a href="#text" class="headerlink" title="text()"></a><code>text()</code></h3><ul>
<li>返回期约，解决为将缓冲区转存得到的 <code>UTF-8</code> 格式字符串</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.text())</span><br><span class="line"> .then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// &lt;!doctype html&gt;&lt;html lang=&quot;en&quot;&gt;</span></span><br><span class="line"><span class="comment">// &lt;head&gt;</span></span><br><span class="line"><span class="comment">// &lt;meta charset=&quot;utf-8&quot;&gt;</span></span><br><span class="line"><span class="comment">// ... </span></span><br><span class="line"><span class="comment">// -------------------------------------</span></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;barbazqux&#x27;</span> &#125;);</span><br><span class="line">request.text().then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// barbazqux</span></span><br></pre></td></tr></table></figure>

<h3 id="json"><a href="#json" class="headerlink" title="json()"></a><code>json()</code></h3><ul>
<li>返回期约，解决为将缓冲区转存得到的 <code>JSON</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com/foo.json&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.json())</span><br><span class="line"> .then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// &#123;&quot;foo&quot;: &quot;bar&quot;&#125;</span></span><br><span class="line"><span class="comment">// -------------------------</span></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>:<span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="built_in">JSON</span>.stringify(&#123; <span class="attr">bar</span>: <span class="string">&#x27;baz&#x27;</span> &#125;) &#125;);</span><br><span class="line">request.json().then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// &#123;bar: &#x27;baz&#x27;&#125; </span></span><br></pre></td></tr></table></figure>

<h3 id="formData"><a href="#formData" class="headerlink" title="formData()"></a><code>formData()</code></h3><ul>
<li>浏览器可以将 <code>FormData</code> 对象序列化/反序列化为主体</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myFormData = <span class="keyword">new</span> FormData();</span><br><span class="line">myFormData.append(<span class="string">&#x27;foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>); </span><br><span class="line"><span class="comment">// 在通过 HTTP 传送时，WebKit 浏览器会将其序列化为下列内容</span></span><br><span class="line"><span class="comment">// ------WebKitFormBoundarydR9Q2kOzE6nbN7eR</span></span><br><span class="line"><span class="comment">// Content-Disposition: form-data; name=&quot;foo&quot;</span></span><br><span class="line"><span class="comment">// bar</span></span><br><span class="line"><span class="comment">// ------WebKitFormBoundarydR9Q2kOzE6nbN7eR--</span></span><br><span class="line"><span class="comment">// -------------------------------</span></span><br><span class="line">fetch(<span class="string">&#x27;https://foo.com/form-data&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.formData())</span><br><span class="line"> .then(<span class="function">(<span class="params">formData</span>) =&gt;</span> <span class="built_in">console</span>.log(formData.get(<span class="string">&#x27;foo&#x27;</span>)); <span class="comment">// bar</span></span><br><span class="line"><span class="keyword">let</span> myFormData = <span class="keyword">new</span> FormData();</span><br><span class="line">myFormData.append(<span class="string">&#x27;foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>:<span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: myFormData &#125;);</span><br><span class="line">request.formData().then(<span class="function">(<span class="params">formData</span>) =&gt;</span> <span class="built_in">console</span>.log(formData.get(<span class="string">&#x27;foo&#x27;</span>))); <span class="comment">// bar</span></span><br></pre></td></tr></table></figure>

<h3 id="arrayBuffer"><a href="#arrayBuffer" class="headerlink" title="arrayBuffer()"></a><code>arrayBuffer()</code></h3><ul>
<li>有时候可能需要以原始二进制格式查看和修改主体</li>
<li>此时可以使用 <code>Body.arrayBuffer()</code> 将主体内容转换为 <code>ArrayBuffer</code> 实例</li>
<li>返回期约，解决为将缓冲区转存得到的 <code>ArrayBuffer</code> 实例</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.arrayBuffer())</span><br><span class="line"> .then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// ArrayBuffer(...) &#123;&#125;</span></span><br><span class="line"><span class="comment">// --------------------------------</span></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>:<span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;abcdefg&#x27;</span> &#125;);</span><br><span class="line"><span class="comment">// 以整数形式打印二进制编码的字符串</span></span><br><span class="line">request.arrayBuffer().then(<span class="function">(<span class="params">buf</span>) =&gt;</span> <span class="built_in">console</span>.log(<span class="keyword">new</span> <span class="built_in">Int8Array</span>(buf)));</span><br><span class="line"><span class="comment">// Int8Array(7) [97, 98, 99, 100, 101, 102, 103] </span></span><br></pre></td></tr></table></figure>

<h3 id="blob"><a href="#blob" class="headerlink" title="blob()"></a><code>blob()</code></h3><ul>
<li>有时候可能需要以原始二进制格式使用主体，不用查看和修改</li>
<li>返回期约，解决为将缓冲区转存得到的 <code>Blob</code> 实例</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.blob())</span><br><span class="line"> .then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// Blob(...) &#123;size:..., type: &quot;...&quot;&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>:<span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;abcdefg&#x27;</span> &#125;);</span><br><span class="line">request.blob().then(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">// Blob(7) &#123;size: 7, type: &quot;text/plain;charset=utf-8&quot;&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="一次性流"><a href="#一次性流" class="headerlink" title="一次性流"></a>一次性流</h3><ul>
<li>因为 <code>Body</code> 混入是构建在可读流之上的，所以主体流<strong>只能使用一次</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>).then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.blob().then(<span class="function">() =&gt;</span> response.blob()));</span><br><span class="line"><span class="comment">// TypeError: Failed to execute &#x27;blob&#x27; on &#x27;Response&#x27;: body stream is locked</span></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line">request.blob().then(<span class="function">() =&gt;</span> request.blob());</span><br><span class="line"><span class="comment">// TypeError: Failed to execute &#x27;blob&#x27; on &#x27;Request&#x27;: body stream is locked </span></span><br></pre></td></tr></table></figure>

<ul>
<li>即使实在读取流的过程中，以上所有的方法也会在被它们调用时给可读流<strong>加锁</strong>，以阻止其他读取器访问</li>
<li><code>req/res.bodyUsed</code> 表示可读流是否已经加锁，不一定已经完全读取</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://foo.com&#x27;</span>).then(<span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span><br><span class="line">   response.blob(); <span class="comment">// 第一次调用给流加锁</span></span><br><span class="line">   response.blob(); <span class="comment">// 第二次调用再次加锁会失败</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// TypeError: Failed to execute &#x27;blob&#x27; on &#x27;Response&#x27;: body stream is locked</span></span><br><span class="line"><span class="keyword">let</span> request = <span class="keyword">new</span> Request(<span class="string">&#x27;https://foo.com&#x27;</span>, &#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>, <span class="attr">body</span>: <span class="string">&#x27;foobar&#x27;</span> &#125;);</span><br><span class="line">request.blob(); <span class="comment">// 第一次调用给流加锁</span></span><br><span class="line">request.blob(); <span class="comment">// 第二次调用再次加锁会失败</span></span><br><span class="line"><span class="comment">// TypeError: Failed to execute &#x27;blob&#x27; on &#x27;Request&#x27;: body stream is locked</span></span><br></pre></td></tr></table></figure>

<h3 id="使用可读流主体"><a href="#使用可读流主体" class="headerlink" title="使用可读流主体"></a>使用可读流主体</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">fetch(<span class="string">&#x27;https://fetch.spec.whatwg.org/&#x27;</span>)</span><br><span class="line"> .then(<span class="function">(<span class="params">response</span>) =&gt;</span> response.body)</span><br><span class="line"> .then(<span class="keyword">async</span> (body) =&gt; &#123;</span><br><span class="line">   <span class="keyword">let</span> reader = body.getReader();</span><br><span class="line">   <span class="keyword">while</span>(<span class="literal">true</span>) &#123;</span><br><span class="line">     <span class="keyword">let</span> &#123; value, done &#125; = <span class="keyword">await</span> reader.read();</span><br><span class="line">     <span class="keyword">if</span> (done) &#123; <span class="keyword">break</span>; &#125;</span><br><span class="line">     <span class="built_in">console</span>.log(value);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// &#123; value: Uint8Array&#123;&#125;, done: false &#125;</span></span><br><span class="line"><span class="comment">// &#123; value: Uint8Array&#123;&#125;, done: false &#125;</span></span><br><span class="line"><span class="comment">// &#123; value: Uint8Array&#123;&#125;, done: false &#125;</span></span><br><span class="line"><span class="comment">// ... </span></span><br></pre></td></tr></table></figure>

<h2 id="BeaconAPI"><a href="#BeaconAPI" class="headerlink" title="BeaconAPI"></a><code>BeaconAPI</code></h2><ul>
<li>为了把尽量多的页面信息传服务器，很分析工具需要在页面生命周期中尽量晚的时候向服务器发送遥测或分析数据</li>
<li>因此理想的情况下是通过浏览器的 <code>unload</code> 事件发送网络请求</li>
<li>但是 <code>unload</code> 事件对于浏览器意味着没有理由再发送任何结果未知的网络请求</li>
<li>在 <code>unload</code> 事件中<strong>任何异步的请求都会被取消</strong></li>
<li>虽然可以使用同步的 <code>ajax</code> 请求强制发送，但是会影响用户体验</li>
</ul>
<h3 id="sendBeacon"><a href="#sendBeacon" class="headerlink" title="sendBeacon()"></a><code>sendBeacon()</code></h3><ul>
<li><p>接收一个 <code>URL</code> 和一个数据有效载荷参数，并会发送一个 <code>POST</code> 请求</p>
</li>
<li><p>并不是只能在页面生命周期末尾使用，而是任何时候都可以使用</p>
</li>
<li><p>调用之后，浏览器会把请求添加到一个内部的请求队列，浏览器会主动发送队列中的请求</p>
</li>
<li><p>浏览器保证在原始页面已经关闭的情况下也会发送请求</p>
</li>
<li><p>状态码、超时和其他网络原因造成的失败完全是不透明的，不能通过编程方式处理</p>
</li>
<li><p>信标（<code>beacon</code>）请求会携带调用 <code>sendBeacon()</code> 时所有相关的 <code>cookie</code></p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 发送 POST 请求</span></span><br><span class="line"><span class="comment">// URL: &#x27;https://example.com/analytics-reporting-url&#x27;</span></span><br><span class="line"><span class="comment">// 请求负载：&#x27;&#123;foo: &quot;bar&quot;&#125;&#x27;</span></span><br><span class="line">navigator.sendBeacon(<span class="string">&#x27;https://example.com/analytics-reporting-url&#x27;</span>, <span class="string">&#x27;&#123;foo: &quot;bar&quot;&#125;&#x27;</span>); </span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">BluesYoung-web</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://bluesyoung-web.gitee.io/blog/2021-02-05-76-%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E5%B8%B8%E7%94%A8%E5%AF%B9%E8%B1%A1.html">https://bluesyoung-web.gitee.io/blog/2021-02-05-76-%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E5%B8%B8%E7%94%A8%E5%AF%B9%E8%B1%A1.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://BluesYoung-web.gitee.io/blog" target="_blank">小黑博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/blog/tags/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%AC%AC%E5%9B%9B%E7%89%88/">JavaScript高级程序设计第四版</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/wx.png" target="_blank"><img class="post-qr-code-img" src="/blog/img/wx.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/blog/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" src="/blog/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2020-12-28-01-历史回顾.html" title="01-历史回顾"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">01-历史回顾</div></div></a></div><div><a href="/blog/2020-12-28-03-script元素.html" title="03-script元素"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">03-script元素</div></div></a></div><div><a href="/blog/2020-12-28-02-实现.html" title="02-实现"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">02-实现</div></div></a></div><div><a href="/blog/2020-12-28-04-文档模式.html" title="04-文档模式"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">04-文档模式</div></div></a></div><div><a href="/blog/2020-12-28-05-语法.html" title="05-语法"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">05-语法</div></div></a></div><div><a href="/blog/2020-12-28-06-变量声明.html" title="06-变量声明"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">06-变量声明</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">BluesYoung-web</div><div class="author-info__description">一枚不善言辞的技术宅</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/BluesYoung-web"><i class="fab fa-gitee"></i><span>点个小星星吧</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BluesYoung-web" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:15171255945@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="移动端软键盘导致布局错乱"/></a><div class="content"><a class="title" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱">移动端软键盘导致布局错乱</a><time datetime="2021-08-24T10:01:20.000Z" title="发表于 2021-08-24 18:01:20">2021-08-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux安装you-get"/></a><div class="content"><a class="title" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get">Linux安装you-get</a><time datetime="2021-08-16T08:07:31.000Z" title="发表于 2021-08-16 16:07:31">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="git删除远程仓库的提交"/></a><div class="content"><a class="title" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交">git删除远程仓库的提交</a><time datetime="2021-08-16T07:52:02.000Z" title="发表于 2021-08-16 15:52:02">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="将pad扩展为电脑的副屏"/></a><div class="content"><a class="title" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏">将pad扩展为电脑的副屏</a><time datetime="2021-08-13T11:44:04.000Z" title="发表于 2021-08-13 19:44:04">2021-08-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux启用SSH服务"/></a><div class="content"><a class="title" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务">Linux启用SSH服务</a><time datetime="2021-08-11T10:50:04.000Z" title="发表于 2021-08-11 18:50:04">2021-08-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By BluesYoung-web</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script> <script src="/blog/js/xkTool.js"></script> <script src="/blog/js/mySelf.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>